package com.livemeter;

import java.util.ArrayList;

import android.app.Activity;
import android.content.SharedPreferences;


/*
 * Class that represents a topic stamp.
 * */
public class Topic 
{
	// private values - serialized
	private long time;
	private int index;
	private String title;

	public Topic(String topicText,long timeOfValue) 
	{
		this.title = topicText;
		
		setTime(timeOfValue);
	}
	
	// TimeStamp
	public long getTime() {return time;}
	public void setTime(long ts) {time = ts;}
	// TimeStamp in ms since 1970
	public long getTimeMS() {return time;}
	
	// actual topic caption
	public String getTopicText() {return title;}

	public int getIndex() {return index;}
	
	// STATIC Topic list - used by master
	private static ArrayList<Topic> allTopics = new ArrayList<Topic>();

	public static void addTopic(Topic t) {Topic.allTopics.add(t);}
	
	public static ArrayList<String> getTopicTitles()
	{
		ArrayList<String> result = new ArrayList<String>();
		for (Topic t : allTopics)
		{
			result.add(t.getTopicText());
		}
		return result;
	}
	public static Topic getTopic(String topicTitle)
	{
		for (Topic t : allTopics)
		{
			if (t.getTopicText().equalsIgnoreCase(topicTitle))
				return t;
		}
		return null;
	}
	
	public static Topic getFirstTopic() {if (allTopics.size() > 0) return allTopics.get(0);else return null;}
	public static Topic getTopicAfter(Topic t)
	{
		int i = allTopics.indexOf(t);
		if (i > -1)
		{
			i += 1;
			if (i < allTopics.size())
				return allTopics.get(i);
		}
		return null;
	}
	
	public static void loadTopics(Activity context)
	{
		Topic.allTopics.clear();
		
		SharedPreferences settings = context.getSharedPreferences("Topics", 0);
	    int countTopics = settings.getInt("topicCount", 0);
	        
	    for(int i = 0; i < countTopics; i++)
	    {
	    	Topic.addTopic(new Topic(settings.getString("topic" + i, "-"), 0));
	    }        
	}
	
	public static void saveTopics(Activity context)
	{
		SharedPreferences settings = context.getSharedPreferences("Topics", 0);
		SharedPreferences.Editor editor = settings.edit();
		
		final int count = Topic.allTopics.size();
		
		editor.putInt("topicCount", count);
		
		for(int i = 0; i < count; i++)
		{
			editor.putString("topic" + i, Topic.allTopics.get(i).title);	
		}
		
		// Commit the edits!
		editor.commit();
	}
	
	public static void clearAll()
	{
		allTopics.clear();
	}
}
